const express = require('express');
const UserModel = require('../../models/UserModel');
const md5 = require('md5');

const router = express.Router();

router.get('/reg',(req,res)=>{
    res.render('reg');
})
router.post('/reg',(req,res)=>{
    // if(req.body.username || req.body.password)
    UserModel.create({...req.body,password:md5(req.body.password)}).then(()=>{
        res.render('success',{msg:"注册成功",url:'/login'});
    },(err)=>{
        res.render('fail',{msg:"用户名已存在",url:'/reg'});
    })
})

router.get('/login',(req,res)=>{
    res.render('login');
})
router.post('/login',(req,res)=>{
    UserModel.findOne({...req.body,password:md5(req.body.password)}).then((data)=>{
        if(data){
            req.session.username = data.username;
            req.session._id = data._id;
            res.render('success',{msg:"登录成功",url:`/account/${data._id}`});
        }else {
            res.render('fail',{msg:"用户名或密码错误",url:`/login`})
        }
    })
})

router.post('/logout',(req,res)=>{
    // 销毁session
    req.session.destroy(()=>{
        res.render('success',{msg:"退出成功",url:"/login"});
    })
})
module.exports = router;
